import { useState, useEffect, useRef } from 'react';
import {
  Box,
  Container,
  Paper,
  IconButton,
  Typography,
  Menu,
  MenuItem,
  Divider
} from '@mui/material';
import { ArrowBack } from '@mui/icons-material';
import { useNavigate } from 'react-router-dom';
import { Message } from '../components/Message';
import { ChatInput } from '../components/ChatInput';
import { Header } from '../components/Header';
import { Loading } from '../components/Loading';
import { sendMessage } from '../services/api';
import axios from 'axios';

/**
 * 聊天消息的类型接口
 * @interface ChatMessage
 * @property {('user' | 'assistant')} role - 消息发送者角色
 * @property {string} content - 消息内容
 * @property {Date} timestamp - 消息时间戳
 * @property {boolean} [isDeleted] - 消息是否被撤回
 * @property {Object} [quotedMessage] - 引用的消息内容
 */
interface ChatMessage {
  role: 'user' | 'assistant';
  content: string;
  timestamp: Date;
  isDeleted?: boolean;
  quotedMessage?: {
    content: string;
    timestamp: Date;
  };
  image?: {
    url: string;
    filename: string;
  };
  location?: {
    latitude: number;
    longitude: number;
    address: string;
    businessAreas?: string;
  };
}

/**
 * 聊天页面组件
 * @component ChatPage
 * @description 实现了消息发送、撤回、引用等功能的聊天界面
 */
export const ChatPage = () => {
  // 状态管理
  const [messages, setMessages] = useState<ChatMessage[]>([]); // 存储聊天消息列表
  const [isLoading, setIsLoading] = useState(false); // 加载状态
  const [error, setError] = useState<string | null>(null); // 错误信息
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null); // 菜单锚点元素
  const [selectedMessageIndex, setSelectedMessageIndex] = useState<number | null>(null); // 选中的消息索引
  const [quotedMessage, setQuotedMessage] = useState<string | null>(null); // 引用的消息内容
  
  // 引用DOM元素，用于滚动到底部
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const navigate = useNavigate();

  /**
   * 监听消息列表变化，自动滚动到底部
   */
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  /**
   * 处理消息引用
   * @param {number} index - 被引用消息的索引
   */
  const handleQuote = (index: number) => {
    const quotedContent = messages[index].content;
    setQuotedMessage(quotedContent);
    setAnchorEl(null);
  };

  /**
   * 发送消息的处理函数
   * @param {string} content - 消息内容
   * @param {File} [imageFile] - 图片文件
   */
  const handleSend = async (content: string, imageFile?: File, location?: { latitude: number; longitude: number; address: string }) => {
    let imageData;
    
    if (imageFile) {
      try {
        // 创建 FormData 对象上传图片
        const formData = new FormData();
        formData.append('image', imageFile);
        
        // 调用上传接口
        const response = await axios.post('/api/upload', formData);
        imageData = {
          url: response.data.url,
          filename: imageFile.name
        };
      } catch (error) {
        setError('图片上传失败');
        return;
      }
    }
  
    const userMessage: ChatMessage = {
      role: 'user',
      content,
      timestamp: new Date(),
      image: imageData,
      location
    };
  
    setMessages(prev => [...prev, userMessage]);
    setIsLoading(true);
    
    try {
      const aiResponse = await sendMessage([
        ...messages.map(m => ({ role: m.role, content: m.content })),
        { role: 'user', content }
      ]);
      
      setMessages(prev => [...prev, {
        role: 'assistant',
        content: aiResponse,
        timestamp: new Date()
      }]);
    } catch (error) {
      setError('发送消息失败，请重试');
    } finally {
      setIsLoading(false);
    }
  };

  /**
   * 撤回消息的处理函数
   * @param {number} index - 要撤回的消息索引
   */
  const handleRevoke = (index: number) => {
    setMessages(prev => {
      const newMessages = [...prev];
      newMessages[index] = { ...newMessages[index], isDeleted: true };
      return newMessages;
    });
    setAnchorEl(null);
  };

  /**
   * 长按消息的处理函数
   * @param {React.MouseEvent} event - 鼠标事件对象
   * @param {number} index - 消息索引
   */
  const handleLongPress = (event: React.MouseEvent, index: number) => {
    event.preventDefault();
    setSelectedMessageIndex(index);
    setAnchorEl(event.currentTarget as HTMLElement);
  };

  /**
   * 菜单开关状态
   */
  const open = Boolean(anchorEl);
  const id = open ? 'simple-popover' : undefined;

  /**
   * 关闭菜单的处理函数
   */
  const handleClose = () => {
    setAnchorEl(null);
  };

  return (
    <Box display="flex" flexDirection="column" height="100vh">
      <Header />
      <Box
        flex={1}
        display="flex"
        flexDirection="column"
        overflow="hidden"
      >
        <Box
          display="flex"
          alignItems="center"
          p={1}
          borderBottom={1}
          borderColor="divider"
        >
          <IconButton onClick={() => navigate('/')}>
            <ArrowBack />
          </IconButton>
          <Typography variant="h6" ml={1}>
            与 AI 对话
          </Typography>
        </Box>

        <Box
          flex={1}
          overflow="auto"
          p={2}
          bgcolor="background.default"
        >
          {messages.map((msg, index) => (
            msg.isDeleted ? ( // 检查是否已撤回
              <Message
                key={index}
                content="消息已撤回"
                isUser={false}
                timestamp={msg.timestamp}
              />
            ) : (
              <Message
                key={index}
                content={msg.content}
                isUser={msg.role === 'user'}
                timestamp={msg.timestamp}
                quotedMessage={msg.quotedMessage}  // 添加引用消息
                onLongPress={(event) => handleLongPress(event, index)}
              />
            )
          ))}
          {isLoading && <Message content="思考中..." isUser={false} timestamp={new Date()} />}
          {error && (
            <Message
              content={error}
              isUser={false}
              timestamp={new Date()}
            />
          )}
          <div ref={messagesEndRef} />
        </Box>

        <ChatInput
          onSend={handleSend}
          disabled={isLoading}
          quotedMessage={quotedMessage}
          onClearQuote={() => setQuotedMessage(null)}
        />
      </Box>


      {/* 气泡框 */}
      <Menu
        id={id}
        anchorEl={anchorEl}
        open={open}
        onClose={handleClose}
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'center',
        }}
        transformOrigin={{
          vertical: 'top',
          horizontal: 'center',
        }}
        sx={{
          '& .MuiMenu-paper': {
            backgroundColor: '#464646', // 更深的灰色背景
            color: 'white',
            borderRadius: 2,
            boxShadow: 3,
            position: 'relative',
            width: 'fit-content',
            minWidth: '80px', // 减小最小宽度
            padding: '4px 0', // 减小内边距
          },
          '& .MuiMenu-paper::after': {
            content: '""',
            position: 'absolute',
            bottom: '-8px',
            left: '50%',
            transform: 'translateX(-50%)',
            width: 0,
            height: 0,
            borderLeft: '6px solid transparent', // 减小三角形大小
            borderRight: '6px solid transparent',
            borderTop: '6px solid #464646',
          },
          '& .MuiMenuItem-root': {
            fontSize: '14px', // 减小文字大小
            padding: '8px 12px', // 减小菜单项的内边距
            minHeight: '32px', // 设置最小高度
            justifyContent: 'center',
          },
        }}
      >

        <MenuItem onClick={() => {
          if (selectedMessageIndex !== null) {
            handleRevoke(selectedMessageIndex);
          }
        }}>
          撤回
        </MenuItem >
        <Divider sx={{ backgroundColor: 'white' }} /> {/* 添加分割线 */}
        <MenuItem onClick={() => {
          if (selectedMessageIndex !== null) {
            handleQuote(selectedMessageIndex);
          }
        }}>
          引用
        </MenuItem>
      </Menu>

    </Box>
  );
};